package com.runnor.common.websys.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runnor.common.websys.system.entity.ApiResult;
import com.runnor.common.websys.system.entity.User;
import com.runnor.common.websys.system.entity.bo.UserBo;
import com.runnor.common.websys.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("api/user")
public class UserController {

    @Autowired
    IUserService userService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('account:list')")
    public ResponseEntity page(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "10") Integer size,
                               User user) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        queryWrapper
                .like(StringUtils.hasText(user.getUsername()), "username", user.getUsername())
                .like(StringUtils.hasText(user.getNikename()), "nikename", user.getNikename())
                .like(StringUtils.hasText(user.getEmail()), "email", user.getEmail())
                .like(StringUtils.hasText(user.getPhone()), "phone", user.getPhone())
                .eq(StringUtils.hasText(user.getRole()), "role", user.getRole())
                .eq(user.getEnabled() != null, "enabled", user.getEnabled())
                .eq("deleted", 0);

        queryWrapper.orderByDesc("createtime");

        Page data = userService.pages(new Page(current, size), queryWrapper);

        return ResponseEntity.ok(ApiResult.ok(data));
    }


    /**
     * 根据id查询角色
     */
    @GetMapping("/getById")
    public ResponseEntity getById(String id) {
        User user = userService.getById(id);
        user.setPassword(null);
        return ResponseEntity.ok(ApiResult.ok(user));
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    @PreAuthorize("hasAuthority('account:add')")
    public ResponseEntity save(User user) {
        //密码加密
        String password = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(password);
        boolean save = userService.save(user);
        return ResponseEntity.ok(ApiResult.ok(save));
    }

    /**
     * 修改 不修改密码，修改其他字段
     */
    @PostMapping("/updateById")
    @PreAuthorize("hasAuthority('account:edit')")
    public ResponseEntity updateById(User user) {

        UpdateWrapper updateWrapper = new UpdateWrapper();

        updateWrapper.set("username", user.getUsername());
        updateWrapper.set("nikename", user.getNikename());
        updateWrapper.set("email", user.getEmail());
        updateWrapper.set("phone", user.getPhone());
        updateWrapper.set("role", user.getRole());
        updateWrapper.set("description", user.getDescription());
        updateWrapper.set("enabled", user.getEnabled());

        updateWrapper.eq("id", user.getId());

        boolean update = userService.update(null, updateWrapper);

        return ResponseEntity.ok(ApiResult.ok(update));
    }

    /**
     * 删除
     */
    @GetMapping("/deletes")
    @PreAuthorize("hasAuthority('account:del')")
    public ResponseEntity deletes(String nos) {
        boolean b = userService.removeBatchByIds(Arrays.asList(nos.split(",")));

        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 删除
     */
    @GetMapping("/removeById")
    @PreAuthorize("hasAuthority('account:del')")
    public ResponseEntity removeById(String no) {
        boolean b = userService.removeById(no);

        return ResponseEntity.ok(ApiResult.ok(b));
    }

    /**
     * 账号唯一校验
     */
    @GetMapping("/selectOneByUserName")
    public ResponseEntity selectOneByUserName(String username, String id) {

        QueryWrapper queryWrapper = new QueryWrapper();

        queryWrapper.eq(StringUtils.hasText(username), "username", username);

        queryWrapper.ne(StringUtils.hasText(id), "id", id);

        User user = userService.getOne(queryWrapper);

        return ResponseEntity.ok(ApiResult.ok(user));
    }

    @PostMapping("/updatePasssword")
    public ResponseEntity updatePasssword(User user) {

        UpdateWrapper updateWrapper = new UpdateWrapper();

        String password = new BCryptPasswordEncoder().encode(user.getPassword());

        updateWrapper.set("password", password);

        updateWrapper.eq("id", user.getId());

        boolean update = userService.update(null, updateWrapper);

        return ResponseEntity.ok(ApiResult.ok(update));
    }

    /**
     * 根据 id 修改 状态
     */
    @GetMapping("/updateEnableById")
    @PreAuthorize("hasAuthority('account:edit')")
    public ResponseEntity updateEnableById(String id, Boolean enabled) {

        UpdateWrapper updateWrapper = new UpdateWrapper();

        updateWrapper.set("enabled", enabled);
        updateWrapper.eq("id", id);

        boolean update = userService.update(null, updateWrapper);

        return ResponseEntity.ok(ApiResult.ok(update));
    }

    /**
     * 校验旧密码 修改新密码
     */
    @PostMapping("/changePassword")
    public ResponseEntity changePassword(UserBo userBo) {

        User user = userService.getById(userBo.getId());

        //判断密码是否一致
        boolean b = new BCryptPasswordEncoder()
                .matches(userBo.getOldpassword(), user.getPassword());

        //密码一致 修改密码
        if (b) {
            String password = new BCryptPasswordEncoder().encode(userBo.getPassword());

            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.set("password", password);
            updateWrapper.eq("id", userBo.getId());

            boolean update = userService.update(null, updateWrapper);

            return ResponseEntity.ok(ApiResult.ok(update));
        } else {
            //密码不一致，返回 false 提示 旧密码错误
            return ResponseEntity.ok(ApiResult.ok(b));
        }

    }

}
